package com.runen.infinitemovement.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.LoginActivity2;
import com.runen.infinitemovement.activity.SportsRecordActivity;
import com.runen.infinitemovement.activity.SportsStatusActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.api.WeatherAPI;
import com.runen.infinitemovement.model.entity.ADDataEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.StartChallengeEntity;
import com.runen.infinitemovement.model.entity.WeatherEntity;
import com.runen.infinitemovement.tool.ADToWebOrActivityUtil;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.CyWeatherUtils;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.track.LocationUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SportsTypeFragment extends Fragment {
    @BindView(R.id.tv_in_all)
    TextView tvInAll;
    @BindView(R.id.tv_sports_type)
    TextView tvSportsType;
    @BindView(R.id.iv_sports_type)
    ImageView ivSportsType;
    @BindView(R.id.ll_start)
    LinearLayout llStart;
    @BindView(R.id.iv_weather)
    ImageView ivWeather;
    @BindView(R.id.tv_weather)
    TextView tvWeather;
    @BindView(R.id.tv_quality)
    TextView tvQuality;
    @BindView(R.id.rci_ad)
    ImageView rciAd;
    private int position;
    private int weatherType;
    private String address;
    private WeatherEntity.ResultBean resultBean;
    private double latitude, longitude;
    private int flag = 0;
    private LocationManager locationManager;

    public static Fragment newInstance(int key) {
        Fragment fragment = new SportsTypeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("point", key);
        fragment.setArguments(bundle);
        return fragment;
    }

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_sports_type, container, false);
            ButterKnife.bind(this, view);
            position = getArguments().getInt("point");
            EventBus.getDefault().register(this);
            initView();
            onPermission();
            getTotalMileage();
        }
        return view;
    }

    private ADDataEntity adDataEntity;

    private void getTotalMileage() {
        String str = "?type=%s";
        new ChallengeAPI().userInitStartChallenge(String.format(str, position == 1 ? 2 : position == 2 ? 1 : 0), new BaseResultCallback<StartChallengeEntity>() {
            @Override
            public void onResponse(StartChallengeEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        tvInAll.setText(String.valueOf(response.data.totalMileage));
                        if (response.data.recommend != null) {
                            adDataEntity = response.data.recommend;
                            if (!TextUtils.isEmpty(adDataEntity.cover)) {
                                rciAd.setVisibility(View.VISIBLE);
                                GlideUtils.loadImage(getActivity(), adDataEntity.cover, rciAd);
                            } else {
                                rciAd.setVisibility(View.GONE);
                            }
                        } else {
                            rciAd.setVisibility(View.GONE);
                        }
                    }
                } else {
                    ToastUtils.showShort(response.msg);
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                }
                super.onError(e, body);
            }
        });

    }


    /**
     * 获取定位数据
     */
    public void getLocation() {
        final LocationUtil locationUtil = new LocationUtil(getActivity());
        locationUtil.start();
        locationUtil.registerLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (null != aMapLocation) {
                    locationUtil.stop();
                    address = aMapLocation.getCity() + "·" + aMapLocation.getAoiName();
                    latitude = aMapLocation.getLatitude();
                    longitude = aMapLocation.getLongitude();
                    SimpleDateFormat aa = new SimpleDateFormat("KK:mm aa", Locale.ENGLISH);
                    String time = aa.format(new Date());
//                    tvDate.set(time);
                    getWeather();
                    initView();
                }
            }
        });
    }

    /**
     * 对接彩云天气接口
     */
    private void getWeather() {
        final String url = String.format(Constant.HOME_WEATHER_ACTION, longitude, latitude);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String weatherJson = WeatherAPI.LoadData(url);
                if (!TextUtils.isEmpty(weatherJson)) {
                    WeatherEntity weatherEntity = new Gson().fromJson(weatherJson, WeatherEntity.class);
                    if (null != weatherEntity) {
                        if (weatherEntity.status.equals("ok")) {
                            if (weatherEntity.result != null) {
                                Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("resultBean", JsonUtils.toJson(weatherEntity.result));
                                message.what = 1;
                                message.setData(bundle);
                                handler.sendMessage(message);
                            }
                        }
                    }
                }
            }
        }).start();
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String string = bundle.getString("resultBean");
                    resultBean = JsonUtils.fromJson(string, WeatherEntity.ResultBean.class);
                    if (null != resultBean) {
                        final int icon = CyWeatherUtils.getWeatherIcon(resultBean.skycon);
                        ivWeather.setImageResource(icon);
                        String temperature = "%s℃";
                        int t = (int) resultBean.temperature;
                        tvWeather.setText(String.format(temperature, t + ""));
                        tvQuality.setText(CyWeatherUtils.getWeatherSkyconName(resultBean.skycon));
                        weatherType = CyWeatherUtils.getWeatherType(resultBean.skycon);
                    }
                    break;
            }
            return false;
        }
    });


    private void initView() {
        String tv_type = "累计%s总里程";
        if (position == 0) {
            tvSportsType.setText(String.format(tv_type, "跑步"));
            GlideUtils.loadImage(getActivity(), CommonUtil.getDrawable(R.mipmap.ico_run_small), ivSportsType);
        } else if (position == 1) {
            tvSportsType.setText(String.format(tv_type, "健走"));
            GlideUtils.loadImage(getActivity(), CommonUtil.getDrawable(R.mipmap.ico_walk_small), ivSportsType);
        } else if (position == 2) {
            tvSportsType.setText(String.format(tv_type, "骑行"));
            GlideUtils.loadImage(getActivity(), CommonUtil.getDrawable(R.mipmap.ico_riding_small), ivSportsType);
        }
    }


    @SuppressLint("WrongConstant")
    public void onPermission() {
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        //判断是否开启了GPS
        boolean ok = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {
            //请求动态权限
            PermissionUtils.permission(PermissionConstants.LOCATION,
                    PermissionConstants.ACCESS_FINE_LOCATION,
                    PermissionConstants.STORAGE,
                    PermissionConstants.CAMERA,
                    PermissionConstants.WRITE_EXTERNAL_STORAGE,
                    PermissionConstants.ACCESS_COARSE_LOCATION)
                    .rationale(new PermissionUtils.OnRationaleListener() {
                        @Override
                        public void rationale(final ShouldRequest shouldRequest) {
                            DialogHelper.showRationaleDialog(shouldRequest);
                        }
                    })
                    .callback(new PermissionUtils.FullCallback() {
                        @Override
                        public void onGranted(List<String> permissionsGranted) {
                            if (flag == 0) {
                                getLocation();
                            } else {
//                                Intent intent2 = new Intent(getActivity(), StartSportsActivity.class);
                                Intent intent2 = new Intent(getActivity(), SportsStatusActivity.class);
                                intent2.putExtra("SPORTS_TYPE", position == 1 ? 2 : position == 2 ? 1 : 0);
                                intent2.putExtra("weatherType", weatherType);
                                startActivity(intent2);
                            }
                        }

                        @Override
                        public void onDenied(List<String> permissionsDeniedForever,
                                             List<String> permissionsDenied) {
                            if (!permissionsDeniedForever.isEmpty()) {
                                DialogHelper.showOpenAppSettingDialog();
                            }
                        }
                    })
                    .request();
        } else {
            //若未开启，弹框让用户选择去开
            new AlertDialog.Builder(getActivity())
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("获取位置失败")
                    .setMessage("未开启位置信息，前往开启")
                    .setCancelable(false)
//                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//
//                        }
//                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 1);
                        }
                    })
                    .show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventBusEntity event) {
        switch (event.getMsg()) {
            case 99:
                getTotalMileage();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.tv_sports_type, R.id.ll_start, R.id.rci_ad})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sports_type:
                Intent intent = new Intent(getActivity(), SportsRecordActivity.class);
                intent.putExtra("type", position == 1 ? 2 : position == 2 ? 1 : 0);
                startActivity(intent);
                break;
            case R.id.ll_start:
                if (CommonUtil.judgeNetIsConnected()) {
                    flag = 1;
                    onPermission();
                } else {
                    ToastUtils.showShort("请连接网络");
                }
                break;
            case R.id.rci_ad:
                if (null != adDataEntity) {
                    ADToWebOrActivityUtil.toType(getActivity(), adDataEntity);
                }
                break;
        }
    }
}
